<template>
  <div style="width: 100%; height: 100%; margin: 0; padding: 0;display:flex;flex-direction:column;">
   <div
      style="
        color: white;
        width: 100%;
        margin: 30px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 50px;
      "
    >
      <div>任务列表</div>
      <el-button
        type="primary"
        @click="addScheduledTaskWin"
        style="width: 200px"
        :style="{
          background:
            'linear-gradient(to right bottom,#1a57b9,#2473e3,#1d57b9)',
        }"
        >创建定时任务</el-button
      >
    </div>
    <div style="width: 100%; display: flex; flex-wrap: wrap;flex:1;">
      <div
        v-for="(item, index) in scheduledTaskArr"
        :key="index"
        style="
          background: white;
          margin: 5px;
          display: flex;
          flex-direction: column;
          height:150px;
          justify-content:space-between;
        "
      >
        {{ item.taskName }}
        <el-button type="danger" @click="delScheduleTask(item)"
          >删除任务</el-button
        >
        <el-button @click="editCommand(item)" type="primary" style="margin: 0"
          >编辑任务</el-button
        >
        <el-button @click="copyCommand(item)" type="primary" style="margin: 0">
          复制任务
        </el-button>
      </div>
    </div>
    <el-dialog title="添加定时命令" :visible.sync="showWin" width="700">
      <div style="width: 100%; display: flex; flex-direction: column">
        <div style="width: 100%; display: flex; align-items: center">
          <div>指令名称</div>
          <div>
            <el-input
              style="margin-left: 10px"
              v-model="addScheduledTaskForm.taskName"
            ></el-input>
          </div>
        </div>
        <div
          style="
            width: 100%;
            display: flex;
            align-items: center;
            margin: 10px 0;
          "
        >
          <div>是否重复</div>
          <el-checkbox
            style="margin-left: 10px"
            v-model="addScheduledTaskForm.needRepeat"
          ></el-checkbox>
        </div>
        <div
          v-if="addScheduledTaskForm.needRepeat == true"
          style="
            width: 100%;
            display: flex;
            align-items: center;
            margin: 10px 0;
          "
        >
          <el-checkbox-group
            v-model="addScheduledTaskForm.repeatGroup"
            @change="changeWorkDayGroup"
          >
            <el-checkbox label="周日" border></el-checkbox>
            <el-checkbox label="周一" border></el-checkbox>
            <el-checkbox label="周二" border></el-checkbox>
            <el-checkbox label="周三" border></el-checkbox>
            <el-checkbox label="周四" border></el-checkbox>
            <el-checkbox label="周五" border></el-checkbox>
            <el-checkbox label="周六" border></el-checkbox>
          </el-checkbox-group>
        </div>
        <div
          style="
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
          "
        >
          <div>执行时间</div>
          <el-date-picker
            @change="changeScheduledTaskDate"
            value-format="yyyy-MM-dd"
            style="margin-left: 10px"
            v-model="addScheduledTaskForm.executeDate"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
          <el-time-picker
            style="margin-left: 10px"
            value-format="HH-mm-ss"
            v-model="addScheduledTaskForm.executeTime"
            placeholder="任意时间点"
          >
          </el-time-picker>
        </div>
        <div
          style="
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
          "
        >
          <div>优先级：</div>
          <div>
            <el-input
              style="margin-left: 10px"
              v-model="addScheduledTaskForm.priority"
            ></el-input>
          </div>
        </div>
        <div
          v-for="(
            taskCommandItem, taskCommandIndex
          ) in addScheduledTaskForm.commandList"
          :key="taskCommandIndex"
          style="display: flex; flex-direction: column; width: 100%"
        >
          <div
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>指令延时</div>
            <div>
              <el-input
                style="margin-left: 10px"
                v-model="taskCommandItem.delay"
              ></el-input>
            </div>
            <div style="margin-left: 20px">ms</div>
          </div>
          <div
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>指令类型</div>
            <el-select
              style="margin-left: 10px"
              @change="changeEventType(taskCommandIndex)"
              v-model="taskCommandItem.eventType"
              placeholder="请选择指令类型"
            >
              <el-option
                v-for="(item1, index1) in instructionArr"
                :key="item1.type"
                :label="item1.type"
                :value="index1"
              >
              </el-option>
            </el-select>
            <el-select
              style="margin-left: 10px"
              v-if="
                taskCommandItem.sonInstructionArr != null &&
                taskCommandItem.sonInstructionArr.length > 0
              "
              v-model="taskCommandItem.sonEventType"
              placeholder="请选择类型"
            >
              <el-option
                v-for="(item1, index1) in taskCommandItem.sonInstructionArr"
                :key="item1"
                :label="item1"
                :value="index1"
              >
              </el-option>
            </el-select>
          </div>
          <div
            v-if="taskCommandItem.eventType <= 2"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>IP地址：</div>
            <div>
              <el-input
                style="margin-left: 10px"
                v-model="taskCommandItem.ipAddress"
              ></el-input>
            </div>
            <div style="margin-left: 10px">端口号：</div>
            <div>
              <el-input
                style="margin-left: 10px"
                v-model="taskCommandItem.port"
              ></el-input>
            </div>
          </div>
          <div
            v-if="taskCommandItem.eventType == 2"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>请求路径</div>
            <div>
              <el-input
                style="margin-left: 10px"
                v-model="taskCommandItem.requestPath"
              >
              </el-input>
            </div>
          </div>
          <div
            v-if="taskCommandItem.eventType <= 2"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>指令数据</div>
            <div>
              <el-input
                style="margin-left: 10px"
                v-model="taskCommandItem.instructionData"
              ></el-input>
            </div>
            <el-checkbox
              v-model="taskCommandItem.hexadecimal"
              style="margin-left: 10px"
              >十六进制</el-checkbox
            >
          </div>
          <div
            v-if="taskCommandItem.eventType == 5"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <div>音频文件</div>
            <el-button
              style="margin-left: 10px"
              @click="clickUploadAudio(taskCommandIndex)"
              >选择音频文件</el-button
            >
            <div
              style="
                cursor: pointer;
                border-bottom: solid 2px black;
                margin: 0 10px;
              "
              @click="jumpToUrl(taskCommandItem.audioFilePath)"
            >
              {{ taskCommandItem.audioFilePath }}
            </div>
            <input
              style="margin-left: 10px"
              :id="'uploadAudio' + taskCommandIndex"
              v-show="false"
              type="file"
              accept="audio/wav"
              @change="uploadAudioFile($event, taskCommandIndex)"
            />
          </div>
          <el-button
            @click="delCommand(taskCommandIndex)"
            type="danger"
            style="margin-bottom: 10px"
            >删除指令</el-button
          >
        </div>
        <el-button @click="addCommand" type="primary">添加指令</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWin = false">取 消</el-button>
        <el-button type="primary" @click="createScheduledTask">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import eventBus from "../util/myEventBus";
import request from "../axios/request";
export default {
  data() {
    return {
      showWin: false,
      addScheduledTaskForm: {
        needRepeat: false,
        executeDate: null,
        repeatGroup: [],
        executeTime: null,
        delay: 0,
        taskName: null,
        commandList: [],
        priority: 1,
      },
      instructionArr: [
        {
          type: "TCP",
          sonType: [],
        },
        {
          type: "UDP",
          sonType: ["单播", "组播", "广播"],
        },
        {
          type: "HTTP",
          sonType: ["GET", "POST"],
        },
        {
          type: "变量赋值",
          sonType: [],
        },
        {
          type: "按扭组合",
          sonType: [],
        },
        {
          type: "播放音频",
          sonType: [],
        },
      ],
      sonInstructionArr: [],
      scheduledTaskArr: [],
    };
  },
  mounted() {
    this.resourceIp = this.extractIPFromURL(window.location.origin);
    this.getAllScheduledTask();
    eventBus.$on("createScheduledTask", this.createScheduledTask);
    eventBus.$on("getAllScheduledTask", this.getAllScheduledTask);
    eventBus.$on("delScheduleTask", this.delScheduleTask);
  },
  beforeDestroy() {
    eventBus.$off("createScheduledTask");
    eventBus.$off("getAllScheduledTask");
    eventBus.$off("delScheduleTask");
  },
  methods: {
    changeScheduledTaskDate() {
      console.log("所选日期被改变");
      this.addScheduledTaskForm.repeatGroup = [];
    },
    changeWorkDayGroup() {
      this.addScheduledTaskForm.executeDate = null;
    },
    jumpToUrl(url) {
      window.location.href = "http://" + this.resourceIp + ":8094/" + url;
    },
    extractIPFromURL(url) {
      // 定义正则表达式来匹配IP地址
      const ipRegex = /(?:\d{1,3}\.){3}\d{1,3}/;

      // 使用正则表达式查找匹配项
      const match = url.match(ipRegex);

      // 返回匹配到的IP地址（如果有的话）
      return match ? match[0] : null;
    },
    clickUploadAudio(index) {
      document.getElementById("uploadAudio" + index).click();
    },
    async uploadAudioFile(event, index) {
      let file = event.target.files[0];
      if (file) {
        let formData = new FormData();
        formData.append("file", file);
        let res = await request({
          url: "/file/api/upload/" + this.resourceIp,
          method: "POST",
          data: formData,
        });
        if (res.data.status == 200) {
          this.addScheduledTaskForm.commandList[index].audioFilePath =
            res.data.data;
          event.target.value = "";
        }
      }
    },
    delCommand(index) {
      this.addScheduledTaskForm.commandList.splice(index, 1);
    },
    addCommand() {
      this.addScheduledTaskForm.commandList.push({
        eventType: null,
        sonEventType: null,
        ipAddress: null,
        port: null,
        requestPath: null,
        instructionData: null,
        sonInstructionArr: [],
        audioFilePath: null,
      });
    },
    async copyCommand(item) {
      let aimCopy = JSON.parse(JSON.stringify(item));
      let res = await request({
        url: "/scheduledTask/api/saveNewScheduledTask",
        method: "POST",
        data: aimCopy,
      });
      if (res.data.status == 200) {
        this.getAllScheduledTask();
      }
    },
    async delScheduleTask(item) {
      this.$store.state.lastMethod = "delScheduleTask";
      this.$store.state.lastData = item;
      let res = await request({
        url: "/scheduledTask/api/delTaskById/" + item.id,
        method: "DELETE",
      });
      if (res.data.status == 200) {
        this.$store.state.checkedPassword = "true";
        this.getAllScheduledTask();
      }
      console.log(item.id);
    },
    editCommand(item) {
      this.showWin = true;
      this.addScheduledTaskForm = item;
      for (
        let index = 0;
        index < this.addScheduledTaskForm.commandList.length;
        index++
      ) {
        const element = this.addScheduledTaskForm.commandList[index];
        element.sonInstructionArr =
          this.instructionArr[element.eventType].sonType;
      }
    },
    async getAllScheduledTask() {
      this.$store.state.lastMethod = "getAllScheduledTask";
      this.$store.state.lastData = null;
      let res = await request({
        url: "/scheduledTask/api/getAllScheduledTask",
        method: "GET",
      });
      if (res.data.status == 200) {
        this.scheduledTaskArr = res.data.data;
      }
    },
    changeEventType(index) {
      console.log(this.addScheduledTaskForm.commandList[index]);
      this.addScheduledTaskForm.commandList[index].sonInstructionArr =
        this.instructionArr[
          this.addScheduledTaskForm.commandList[index].eventType
        ].sonType;
    },
    addScheduledTaskWin() {
      this.showWin = true;
      this.addScheduledTaskForm = {
        needRepeat: false,
        executeDate: null,
        repeatGroup: [],
        executeTime: null,
        taskName: null,
        delay: 0,
        commandList: [],
        priority: 1,
      };
    },
    async createScheduledTask() {
      if (
        this.addScheduledTaskForm.executeTime == null ||
        this.addScheduledTaskForm.taskName == null
      ) {
        this.$message.error("请填写信息后提交");
        return;
      }
      this.$store.state.lastMethod = "createScheduledTask";
      this.$store.state.lastData = null;
      let res = null;
      if (this.addScheduledTaskForm.id == null) {
        res = await request({
          url: "/scheduledTask/api/saveNewScheduledTask",
          method: "POST",
          data: this.addScheduledTaskForm,
        });
      } else {
        res = await request({
          url: "/scheduledTask/api/updateScheduleTaskById",
          method: "POST",
          data: this.addScheduledTaskForm,
        });
      }
      if (res.data.status == 200) {
        this.$store.state.checkedPassword = "true";
        this.getAllScheduledTask();
        this.showWin = false;
      }
    },
  },
};
</script>

<style>
</style>